package service

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"lot_admin_api/api"
	"lot_admin_api/internal/consts"
	"lot_admin_api/internal/dao"
	"lot_admin_api/internal/model"
	GenInt64Id "lot_admin_api/utility/genInt64IdOfString"
	"lot_admin_api/utility/paging"
	"lot_admin_api/utility/response"
)

type sUser struct{}

var (
	insUser = sUser{}
)

func User() *sUser {
	return &insUser
}

func (s *sUser) UserList(ctx context.Context, req *api.UserListReq) (res *model.UserListRes, err error) {
	findList := make([]*model.UserInfoRes, 0)
	startNum, endNum := paging.Paging(req.Paging)
	//staffInfo := cache.StaffInfo(ctx)
	keyWord := "%" + req.KeyWord + "%" // 定义模糊查询的字段 能查询用户名和手机号
	condition := g.Map{
		"id":                                req.Id, // 用户id
		"(username like ? OR phone like ?)": g.Slice{keyWord, keyWord},
	}
	r := g.RequestFromCtx(ctx)
	// 获取用户列表
	if err = dao.LotUser.Ctx(ctx).OmitEmpty().WithAll().Where(condition).OrderDesc("created_at").Limit(startNum, endNum).Scan(&findList); err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), err.Error())
	}
	// 获取总条数
	countInfo, err := dao.LotUser.Ctx(ctx).OmitEmpty().Where(condition).Count()
	putCount := paging.PutCount(req.Paging, countInfo)
	res = &model.UserListRes{
		List:    findList,
		PutPage: putCount,
	}
	return res, err
}

// GiveUserMoney  给用户赠送金额
func (s *sUser) GiveUserMoney(ctx context.Context, req *model.GiftAmount) (id string, err error) {
	r := g.RequestFromCtx(ctx)
	var findUserInfo *model.UserInfoDetails
	//userInfo := cache.StaffInfo(ctx)
	//  查询用户是否存在
	err = dao.LotUserInfo.Ctx(ctx).WithAll().Where("user_id", req.Id).Scan(&findUserInfo)
	if findUserInfo == nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "没有当前用户的详情")
	}
	// 赠送金额 的值
	updateInfo := g.Map{
		"give_recharge": req.GiveRecharge + findUserInfo.GiveRecharge,
	}
	// 赠送记录相关的值
	recordInfo := g.Map{
		"id":         GenInt64Id.GenInt64IdOfString(), // 记录id
		"give_money": req.GiveRecharge,                // 赠送金额
		//"give_user":  userInfo.Id,                     // 赠送人id
		//"company_id": userInfo.CompanyId,              // 赠送人公司
		"user_id":   req.Id, // 获取人id
		"give_type": 3,      // 赠送类型
	}
	// 增加一条赠送记录
	if _, err = dao.LotRechargeRecord.Ctx(ctx).Save(&recordInfo); err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), err.Error())
	}

	// 修改用户的赠送金额
	if _, err = dao.LotUserInfo.Ctx(ctx).Where("user_id", req.Id).Update(&updateInfo); err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), err.Error())
	}

	return req.Id, err
}

// SearchInfo 通过用户Id获取用户详情
func (s *sUser) SearchInfo(ctx context.Context, Id string) (res *model.UserInfoRes, err error) {
	r := g.RequestFromCtx(ctx)
	err = dao.LotUser.Ctx(ctx).WithAll().Where("id", Id).Scan(&res)
	if res == nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "当前用户不存在")
	}
	return res, err
}
